from soj.settings.compare.token.token import TOKEN_PROVIDER
from soj.settings.compare.common import MAX_COMPARE_TIME
from soj.builtin.compare.common import ensure_file,ResultCode,SPJCompareResult,translate_msg
from pathlib import Path
import subprocess as sp
#Testlib support
class SPJCompare:
    def __init__(self,file_i:Path,file_p:Path,file_j:Path,spj_exe:Path,file_r:Path|None=None):
        raise NotImplementedError("Special Judge is NOT supported now")
        ensure_file(file_p)
        ensure_file(file_j)
        ensure_file(file_i)
        ensure_file(spj_exe)
        if file_r is not None:
            ensure_file(file_r)
            self.file_r=file_r
        else: self.file_r=None
        self.file_p=file_p.resolve().absolute()
        self.file_j=file_j.resolve().absolute()
        self.file_i=file_i.resolve().absolute()
        self.spj=spj_exe.resolve().absolute()
    def compare(self)->SPJCompareResult:
        try:
            result=sp.run(args=[
                self.spj,
                self.file_i,
                self.file_p,
                self.file_j
            ]+([] if self.file_r is None else [self.file_r]),
                executable=self.spj,timeout=MAX_COMPARE_TIME,capture_output=True,text=True)
        except TimeoutError as e:
            return {
                'result_code':ResultCode.FAILED,
                'msg':'[SE:TokenCompare] Comparator timed out'
            }
        except Exception as e:
            return {
                'result_code':ResultCode.FAILED,
                'msg':'[SE:TokenCompare] Unknown exception raised'
            }
        msg=translate_msg(result.stdout)
        return {
            'result_code':(ResultCode.ACCEPTABLE if result.returncode==0 
                           else (ResultCode.UNACCEPTABLE if result.returncode==1 else ResultCode.FAILED)),
            'msg':msg
        }